<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/*
 * 让ci继承自己的类库 
 * ######################################
 * 这个类里面写权限代码
 * 不需要走权限的控制类还是CI_Controller
 * ###################################
 * @author Cuil <lntschampion@163.com>
 * @date 2016-02-15
 */

class MY_Controller extends CI_Controller {

    //用户
    public $userid = "";
    public $username = "";
    public $table_ = "";
    public $siteclass;
    public $sitemethod;

    function __construct() {
        parent::__construct();
        $this->load->model('M_user');
        //登录验证
//        $this->isLogin();
        $RTR = & load_class('Router');
        $this->siteclass = $RTR->fetch_class();
        $this->sitemethod = $RTR->fetch_method();
    }
    
    //检查是否登录了
    private function isLogin() {
        if (!isset($_COOKIE['user_id']) || !isset($_COOKIE['user_name'])) {
            //退出登录
            // showMsg('登录过期，请重新登录1', 'login/index', 2, '', 'logout');
            header("Location:/login/index");exit;
        }

        //登录了
        $this->userid = isset($_COOKIE['user_id']) ? DES_ADMIN::decrypt($_COOKIE['user_id']) : '';
        $this->username = isset($_COOKIE['user_name']) ? DES_ADMIN::decrypt($_COOKIE['user_name']) : '';
        $userkey = isset($_COOKIE['user_key']) ? DES_ADMIN::decrypt($_COOKIE['user_key']) : '';
        $action_time = isset($_COOKIE['action_time']) ? DES_ADMIN::decrypt($_COOKIE['action_time']) : '';
        //验证cookie key
	//	var_dump( $this->userid);
        if (md5($this->userid . $this->username . ADMINUSERKEY) != $userkey || $action_time <= $this->time) {
            //退出登录
            // showMsg('登录过期，请重新登录2', 'login/index', 2, '', 'logout');
            header("Location:/login/index");exit;
        }

        //cookie延期
        $arr = array(
            'user_id' => DES_ADMIN::encrypt($this->userid),
            'user_name' => DES_ADMIN::encrypt($this->username),
            'user_key' => DES_ADMIN::encrypt(md5($this->userid . $this->username . ADMINUSERKEY)),
            'action_time' => DES_ADMIN::encrypt($this->time + COOKIE_EXPIRE_TIME)
        );
        ssetcookie($arr, COOKIE_EXPIRE_TIME, '/', COOKIE_DOMAIN_PLAY);
    }

    //根据表结构导出
    public function table_export($table_name) {
        $query = $this->db->get($table_name);

        if (!$query)
            return false;
        // Starting the PHPExcel library
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/IOFactory');

        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setTitle("export")->setDescription("none");

        $objPHPExcel->setActiveSheetIndex(0);
        // Field names in the first row
        $fields = $query->list_fields();
        $col = 0;
        foreach ($fields as $field) {
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
            $col++;
        }
        // Fetching the table data
        $row = 2;
        foreach ($query->result() as $data) {
            $col = 0;
            foreach ($fields as $field) {
                $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field);
                $col++;
            }

            $row++;
        }

        $objPHPExcel->setActiveSheetIndex(0);

        $objWriter = IOFactory :: createWriter($objPHPExcel, 'Excel5');
        // Sending headers to force the user to download the file
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="Products_' . date('dMy') . '.xls"');
        header('Cache-Control: max-age=0');

        $objWriter->save('php://output');
    }

    //根据数据格式导出
    //$title 标题 array('name'=>'fans','mobile'=>'156');
    //$data  数据 list;
    //$filename  文件名称
    public function excel_export($title, $data, $filename) {

        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/IOFactory');

        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setTitle("export")->setDescription("none");

        $objPHPExcel->setActiveSheetIndex(0);

        $col = 0;
        foreach ($title as $field) {
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
            $objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(20);
            $col++;
        }

        $row = 2;
        foreach ($data as $val) {
            $col = 0;
            foreach ($title as $k => $v) {
                $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $val[$k]);
                $col++;
            }
            $row++;
        }

        $objPHPExcel->setActiveSheetIndex(0);

        $objWriter = IOFactory :: createWriter($objPHPExcel, 'Excel5');
        ob_end_clean();//清除缓冲区,避免乱码
        header('Content-Type: application/vnd.ms-excel');
        $filename = $filename . date('Ymd');
        $filename = iconv("UTF-8", "GB2312//IGNORE", $filename);
        header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
        header('Cache-Control: max-age=0');

        $objWriter->save('php://output');
    }


    /**
     * 模拟post进行url请求
     * @param string $url
     * @param string $param
     */
    public function request_post($url = "", $param = "", $header = "") {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        // 增加 HTTP Header（头）里的字段 
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        // 终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($ch); //运行curl

        curl_close($ch);
        return $data;
    }

    /**
     * 获取所有顶级部门以及子部门
     * @param string $data 所有分类
     * @param string $pId 分类ID
     */
    function get_tree($data, $pId)
    {
        $tree = '';
        foreach($data as $k => $v)
        {
            if($v['ParentID'] == $pId)
            {
                //父亲找到儿子
                $v['arr'] = $this->get_tree($data, $v['ID']);
                $tree[] = $v;
                //unset($data[$k]);
            }
        }
        return $tree;
    }

}
